Dino Geek, try to help you

How does the `yield` function work in PHP?


Certainly! The `yield` function in PHP is an essential feature introduced in PHP 5.5, providing support for generators—a simple way to iterate through data without the need to build an array in memory. Here’s how it works:

In PHP, a generator is a special type of iterator. Unlike a traditional function that returns a single value, a generator produces a sequence of values over time, allowing the creation of simple iterators with less overhead and in a more memory-efficient manner. This is thanks to the `yield` keyword. When a generator function is called, it returns an object that can be iterated over.

Here’s a simple example to illustrate how `yield` works:

```
function simpleGenerator() { yield ‘first’; yield ‘second’; yield ‘third’;
}

foreach (simpleGenerator() as $value) { echo $value, PHP_EOL;
}
```

Output:
```
first
second
third
```

In this example, the `simpleGenerator` function uses the `yield` keyword to produce values. Each time the generator object is iterated over, the function executes until it encounters a `yield` statement, then returns the yielded value. When the generator is iterated over again, it resumes execution right after the `yield` statement.

Generators are particularly useful for processing large datasets or streaming data where loading everything into memory is impractical. By yielding values one at a time, memory usage is minimized since values are produced and processed on the fly.

Consider another example where we use `yield` to read lines from a file:

```
function readLines($file) { $handle = fopen($file, ‘r’); if (!$handle) { throw new Exception(“Could not open file: $file”); } while (($line = fgets($handle)) !== false) { yield $line; } fclose($handle);
}

foreach (readLines(‘example.txt’) as $line) { echo $line;
}
```

This approach is memory efficient. Instead of loading the entire file into memory, it reads and processes one line at a time.

Generators can also yield key-value pairs by including a key in the `yield` statement:

```
function keyValueGenerator() { yield ‘a’ => 1; yield ‘b’ => 2; yield ‘c’ => 3;
}

foreach (keyValueGenerator() as $key => $value) { echo “Key: $key, Value: $value”, PHP_EOL;
}
```

Output:
```
Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3
```

In this case, the generator yields each key-value pair, making it suitable for associative arrays.

Beyond yielding values and keys, `yield` can also be used in conjunction with `yield from` to delegate generation to another generator. This is especially useful for breaking down large generator functions into smaller, more manageable pieces:

```
function subGenerator() { yield 1; yield 2;
}

function mainGenerator() { yield 0; yield from subGenerator(); yield 3;
}

foreach (mainGenerator() as $value) { echo $value, PHP_EOL;
}
```

Output:
```
0
1
2
3
```

Here, `mainGenerator` delegates part of its operation to `subGenerator` using `yield from`, seamlessly integrating its yielded values into the main sequence.

Sources:

1. The official PHP documentation on generators: [PHP Generators](https://www.php.net/manual/en/language.generators.overview.php)
2. PHP: The Right Way – A quick reference to best practices and PHP standards: [Generators](https://phptherightway.com/#generators)

In conclusion, the `yield` function in PHP provides a powerful tool for creating iterators without the memory burden of arrays, making it invaluable for working with large datasets or streams of data. Its simplicity and efficiency make it a staple for modern PHP developers aiming to write more performant and maintainable code.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use